package com.xxl.job.admin.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.PageUtil;
import com.dimples.dd.common.constant.DDServerConstant;
import com.dimples.dd.common.model.Option;
import com.dimples.dd.common.pojo.PageParam;
import com.dimples.dd.common.pojo.PageResult;
import com.dimples.dd.common.result.CommonResult;
import com.dimples.dd.common.result.ResultCode;
import com.dimples.dd.log.core.annotation.ApiLog;
import com.xxl.job.admin.controller.annotation.PermissionLimit;
import com.xxl.job.admin.core.model.XxlJobGroup;
import com.xxl.job.admin.core.model.XxlJobRegistry;
import com.xxl.job.admin.core.util.I18nUtil;
import com.xxl.job.admin.dao.XxlJobGroupDao;
import com.xxl.job.admin.dao.XxlJobInfoDao;
import com.xxl.job.admin.dao.XxlJobRegistryDao;
import com.xxl.job.core.enums.RegistryConfig;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * job group controller
 *
 * @author xuxueli 2016-10-02 20:52:56
 */
@Tag(name = "执行器管理")
@Controller
@RequestMapping("/job-group")
public class JobGroupController {

    private static final Logger logger = LoggerFactory.getLogger(JobGroupController.class);

    @Resource
    public XxlJobInfoDao xxlJobInfoDao;
    @Resource
    public XxlJobGroupDao xxlJobGroupDao;
    @Resource
    private XxlJobRegistryDao xxlJobRegistryDao;

    @RequestMapping
    @PermissionLimit(adminuser = true)
    public String index(Model model) {
        return "jobgroup/jobgroup.index";
    }

    @Operation(summary = "获取执行器列表")
    @GetMapping("/page")
    @ResponseBody
    @PermissionLimit(adminuser = true)
    @ApiLog(applicationName = DDServerConstant.DD_XXL_JOB, responseEnable = true)
    @PreAuthorize("@ss.hasPerm('system:job-group:query')")
    public PageResult<XxlJobGroup> pageList(PageParam pageParam, String appname, String title) {

        // page query
        PageUtil.setOneAsFirstPageNo();
        int start = PageUtil.getStart(pageParam.getCurrent(), pageParam.getSize());
        int length = pageParam.getSize();
        List<XxlJobGroup> list = xxlJobGroupDao.pageList(start, length, appname, title);

        int list_count = xxlJobGroupDao.pageListCount(start, length, appname, title);

        return PageResult.success(list, list_count);
    }

    @Operation(summary = "执行器下拉列表")
    @GetMapping("/options")
    @ResponseBody
    @PreAuthorize("@ss.hasPerm('system:job-group:query')")
    public CommonResult<List<Option<Integer>>> listRoleOptions() {
        List<Option<Integer>> result = CollUtil.newArrayList();
        List<XxlJobGroup> jobGroups = this.xxlJobGroupDao.findAll();
        for (XxlJobGroup jobGroup : jobGroups) {
            result.add(new Option<>(jobGroup.getId(), jobGroup.getTitle()));
        }
        return CommonResult.success(result);
    }

    @Operation(summary = "新增执行器")
    @PostMapping
    @ResponseBody
    @PermissionLimit(adminuser = true)
    @ApiLog(applicationName = DDServerConstant.DD_XXL_JOB, responseEnable = true)
    @PreAuthorize("@ss.hasPerm('system:job-group:query')")
    public CommonResult<String> save(@RequestBody XxlJobGroup xxlJobGroup) {

        // valid
        if (xxlJobGroup.getAppname() == null || xxlJobGroup.getAppname().trim().isEmpty()) {
            return CommonResult.error("500", (I18nUtil.getString("system_please_input") + "AppName"));
        }
        if (xxlJobGroup.getAppname().length() < 4 || xxlJobGroup.getAppname().length() > 64) {
            return CommonResult.error("500", I18nUtil.getString("jobgroup_field_appname_length"));
        }
        if (xxlJobGroup.getAppname().contains(">") || xxlJobGroup.getAppname().contains("<")) {
            return CommonResult.error("500", "AppName" + I18nUtil.getString("system_unvalid"));
        }
        if (xxlJobGroup.getTitle() == null || xxlJobGroup.getTitle().trim().isEmpty()) {
            return CommonResult.error("500", (I18nUtil.getString("system_please_input") + I18nUtil.getString("jobgroup_field_title")));
        }
        if (xxlJobGroup.getTitle().contains(">") || xxlJobGroup.getTitle().contains("<")) {
            return CommonResult.error("500", I18nUtil.getString("jobgroup_field_title") + I18nUtil.getString("system_unvalid"));
        }
        if (xxlJobGroup.getAddressType() != 0) {
            if (xxlJobGroup.getAddressList() == null || xxlJobGroup.getAddressList().trim().isEmpty()) {
                return CommonResult.error("500", I18nUtil.getString("jobgroup_field_addressType_limit"));
            }
            if (xxlJobGroup.getAddressList().contains(">") || xxlJobGroup.getAddressList().contains("<")) {
                return CommonResult.error("500", I18nUtil.getString("jobgroup_field_registryList") + I18nUtil.getString("system_unvalid"));
            }

            String[] addresss = xxlJobGroup.getAddressList().split(",");
            for (String item : addresss) {
                if (item == null || item.trim().isEmpty()) {
                    return CommonResult.error("500", I18nUtil.getString("jobgroup_field_registryList_unvalid"));
                }
            }
        }

        // process
        xxlJobGroup.setUpdateTime(new Date());

        int ret = xxlJobGroupDao.save(xxlJobGroup);
        return (ret > 0) ? CommonResult.success(null) : CommonResult.error(ResultCode.SYSTEM_EXECUTION_ERROR);
    }

    @Operation(summary = "更新执行器")
    @PutMapping("/{id}")
    @ResponseBody
    @PermissionLimit(adminuser = true)
    @ApiLog(applicationName = DDServerConstant.DD_XXL_JOB, responseEnable = true)
    @PreAuthorize("@ss.hasPerm('system:job-group:update')")
    public CommonResult<String> update(@PathVariable Integer id, @RequestBody XxlJobGroup xxlJobGroup) {
        // valid
        if (xxlJobGroup.getAppname() == null || xxlJobGroup.getAppname().trim().isEmpty()) {
            return CommonResult.error("500", (I18nUtil.getString("system_please_input") + "AppName"));
        }
        if (xxlJobGroup.getAppname().length() < 4 || xxlJobGroup.getAppname().length() > 64) {
            return CommonResult.error("500", I18nUtil.getString("jobgroup_field_appname_length"));
        }
        if (xxlJobGroup.getTitle() == null || xxlJobGroup.getTitle().trim().isEmpty()) {
            return CommonResult.error("500", (I18nUtil.getString("system_please_input") + I18nUtil.getString("jobgroup_field_title")));
        }
        if (xxlJobGroup.getAddressType() == 0) {
            // 0=自动注册
            List<String> registryList = findRegistryByAppName(xxlJobGroup.getAppname());
            StringBuilder addressListStr;
            if (registryList != null && !registryList.isEmpty()) {
                Collections.sort(registryList);
                addressListStr = new StringBuilder();
                for (String item : registryList) {
                    addressListStr.append(item).append(",");
                }
                addressListStr = new StringBuilder(addressListStr.substring(0, addressListStr.length() - 1));
                xxlJobGroup.setAddressList(addressListStr.toString());
            }
        } else {
            // 1=手动录入
            if (xxlJobGroup.getAddressList() == null || xxlJobGroup.getAddressList().trim().isEmpty()) {
                return CommonResult.error("500", I18nUtil.getString("jobgroup_field_addressType_limit"));
            }
            String[] addresss = xxlJobGroup.getAddressList().split(",");
            for (String item : addresss) {
                if (item == null || item.trim().isEmpty()) {
                    return CommonResult.error("500", I18nUtil.getString("jobgroup_field_registryList_unvalid"));
                }
            }
        }

        // process
        xxlJobGroup.setUpdateTime(new Date());

        int ret = xxlJobGroupDao.update(xxlJobGroup);
        return (ret > 0) ? CommonResult.success(null) : CommonResult.error(ResultCode.SYSTEM_EXECUTION_ERROR);
    }

    private List<String> findRegistryByAppName(String appnameParam) {
        HashMap<String, List<String>> appAddressMap = new HashMap<>();
        List<XxlJobRegistry> list = xxlJobRegistryDao.findAll(RegistryConfig.DEAD_TIMEOUT, new Date());
        if (list != null) {
            for (XxlJobRegistry item : list) {
                if (RegistryConfig.RegistType.EXECUTOR.name().equals(item.getRegistryGroup())) {
                    String appname = item.getRegistryKey();
                    List<String> registryList = appAddressMap.get(appname);
                    if (registryList == null) {
                        registryList = new ArrayList<String>();
                    }

                    if (!registryList.contains(item.getRegistryValue())) {
                        registryList.add(item.getRegistryValue());
                    }
                    appAddressMap.put(appname, registryList);
                }
            }
        }
        return appAddressMap.get(appnameParam);
    }

    @Operation(summary = "删除执行器")
    @DeleteMapping("/{id}")
    @ResponseBody
    @PermissionLimit(adminuser = true)
    @ApiLog(applicationName = DDServerConstant.DD_XXL_JOB, responseEnable = true)
    @PreAuthorize("@ss.hasPerm('system:job-group:delete')")
    public CommonResult<String> remove(@PathVariable int id) {

        // valid
        int count = xxlJobInfoDao.pageListCount(0, 10, id, -1, null, null, null);
        if (count > 0) {
            return CommonResult.error("500", I18nUtil.getString("jobgroup_del_limit_0"));
        }

        List<XxlJobGroup> allList = xxlJobGroupDao.findAll();
        if (allList.size() == 1) {
            return CommonResult.error("500", I18nUtil.getString("jobgroup_del_limit_1"));
        }

        int ret = xxlJobGroupDao.remove(id);
        return (ret > 0) ? CommonResult.success(null) : CommonResult.error(ResultCode.SYSTEM_EXECUTION_ERROR);
    }

    @Operation(summary = "根据id查询执行器")
    @GetMapping("/{id}/form")
    @ResponseBody
    @PermissionLimit(adminuser = true)
    @ApiLog(applicationName = DDServerConstant.DD_XXL_JOB, responseEnable = true)
    @PreAuthorize("@ss.hasPerm('system:job-group:query')")
    public CommonResult<XxlJobGroup> loadById(@PathVariable int id) {
        XxlJobGroup jobGroup = xxlJobGroupDao.load(id);
        if (jobGroup == null) {
            return CommonResult.error(ResultCode.DATA_NOT_FOUND);
        }
        return CommonResult.success(jobGroup);
    }

    @Operation(summary = "根据id查询执行器")
    @GetMapping("/{id}/registry")
    @ResponseBody
    @PermissionLimit(adminuser = true)
    @ApiLog(applicationName = DDServerConstant.DD_XXL_JOB, responseEnable = true)
    @PreAuthorize("@ss.hasPerm('system:job-group:query')")
    public PageResult<XxlJobGroup.RegistryBean> selectExecutorStatus(@PathVariable int id) {
        XxlJobGroup jobGroup = this.loadById(id).getData();

        return PageResult.success(jobGroup.getRegistryList());
    }

}
